package io.renren.modules.zjwl.service.impl;

import io.renren.modules.device.entity.DeviceEntity;
import io.renren.modules.device.service.DeviceService;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.zjwl.dao.SimCardDao;
import io.renren.modules.zjwl.service.SimCardService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.zjwl.dao.DeviceAgentDao;
import io.renren.modules.zjwl.entity.DeviceAgentEntity;
import io.renren.modules.zjwl.service.DeviceAgentService;


@Service("deviceAgentService")
public class DeviceAgentServiceImpl extends ServiceImpl<DeviceAgentDao, DeviceAgentEntity> implements DeviceAgentService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private SimCardService simCardService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<DeviceAgentEntity> queryWrapper = new QueryWrapper<>();
        if (params.containsKey("name")
                && StringUtils.isNotEmpty(params.get("name").toString())) {
            queryWrapper.like("name", params.get("name").toString());
        }
        IPage<DeviceAgentEntity> page = this.page(
                new Query<DeviceAgentEntity>().getPage(params),
                queryWrapper
        );
        List<DeviceAgentEntity> agentEntityList = page.getRecords();
        agentEntityList.forEach(agent -> {
            QueryWrapper<SysUserEntity> userEntityQueryWrapper = new QueryWrapper<>();
            userEntityQueryWrapper.eq("agent_id", agent.getId());
            List<SysUserEntity> userEntityList = sysUserService.list(userEntityQueryWrapper);
            agent.setUserCount(userEntityList.size());
            SimCardDao simCardDao = (SimCardDao) simCardService.getBaseMapper();
            List<String> deviceIdList = simCardDao.findDeviceIdByAgentId(agent.getId());
            Set<String> deviceIdSet = new HashSet<>(deviceIdList);
            deviceIdSet.remove(null);
            deviceIdSet.remove("");
            agent.setDeviceCount(deviceIdSet.size());
//            QueryWrapper<DeviceEntity> deviceEntityQueryWrapper=new QueryWrapper<>();
//            deviceEntityQueryWrapper.in("")
        });
        return new PageUtils(page);
    }

}